import {
	storage
} from '@/utils/localStorage.js';
import crypto from 'crypto';
import uuidv1 from 'uuid/v1';
import config from '@/request/config.js';
import base64 from '@/utils/base64.js'
import {
	resolve
} from 'dns/promises';
import {
	rejects
} from 'assert';
/*
 * @Description: 请求方法
 * @Author: zxy
 * @EditTime: 2023-07-13 17:29:40
 * @LastEditTime: 2023-07-13 17:29:40
 */
/**
 * @Function
 * @param {Object} options - 请求配置项
 * @prop {String} options.url - 请求路径
 * @prop {String} options.method - 请求方式
 * @prop {String} options.header - 请求头
 * @prop {Object} options.data - 请求参数
 */

const http = ((options, showCustomLoading = false, timeout = 60000) => {
	return new Promise((resolve, reject) => {
		// platform 区分开发平台
		var platform = ''
		// #ifdef MP-WEIXIN
		platform = 'wx'
		// #endif

		// #ifdef MP-ALIPAY
		platform = 'zfb'
		// #endif

		if (typeof(options) != 'object') {
			throw ('参数错误');
		}
		// let key = '';
		// if (storage.getKey()) {
		// 	key = storage.getKey() || '';
		// }
		// let s_data = sort_ascii(options.data);
		// // console.log('获取到s_data:' + s_data);

		// if (s_data != null && s_data != "") {
		// 	s_data.substr(0, s_data.length - 1);
		// }
		// const md5 = crypto.createHash('md5');
		// let md5_data = md5.update(key + s_data).digest('hex');
		// let uuid = uuidv1();

		//获取当前时间戳
		var timestamp = Date.parse(new Date());
		timestamp = timestamp / 1000 + '';
		let reqHead = {
			Authorization: storage.getUserToken(),
			// sign: md5_data,
			// uuid: uuid,
			timestamp: timestamp,
			platform: platform,
		};
		console.log("post请求头", reqHead);
		if (showCustomLoading) {
			uni.showLoading({
				title: '正在加载...',
				mask: true
			})
		}

		uni.request({
			url: options.url,
			method: options.method ? options.method : 'POST',
			header: options.header ? options.header : reqHead,
			data: options.data,
			timeout: timeout,
			success: res => {
				console.log("公共请求返回值", res)
				resolve(res)
			},
			fail: (e) => {
				console.log("请求失败", e);
				reject(e)
			}
		})
	}).then((res) => {
		handleData(res, options)
	}, (err) => {
		options.fail && options.fail(err);
	}).finally(() => {
		options.complete && options.complete();
		if (showCustomLoading) {
			uni.hideLoading();
		}
	})
})

//处理返回数据
const handleData = (res, options) => {
	var platform = ''
	// #ifdef MP-WEIXIN
	platform = 'wx'
	// #endif

	// #ifdef MP-ALIPAY
	platform = 'zfb'
	// #endif
	let reqHead = {
		platform: platform
	};
	//仅成功时回调
	if (res.statusCode === 200) {
		//token超时后自动使用code进行登录
		if (res.data.code === '11111') {
			console.log("公共post接口发现token失效，静默登录");

			uni.login({
				success: rs => {
					if (rs.code) {
						//微信登录成功 已拿到code  
						// console.log("拿到code,去登录", rs);
						//去登录
						uni.request({
							url: config.login.loginByCodeUrl,
							method: 'POST',
							header: reqHead,
							data: {
								code: rs.code,
								phone: storage.getPhone(),
							},
							success: res => {
								console.log("静默登录返回值", res);
								if (res.statusCode === 200 && '10000' == res.data.code) {
									//成功后更新缓存数据
									//支付宝 手机号需要脱敏
									// // #ifdef MP-ALIPAY
									// var encrypt = res.data.data.random;
									// var realPhone = base64.decode(encrypt);
									// // console.log('获取到解密结果:' + realPhone);
									// //真实手机号
									// storage.setPhone(realPhone);
									// //中间隐藏手机号
									// storage.setPhoneDes(res.data.data.phone);
									// // #endif


									//微信
									// #ifdef MP-WEIXIN
									//真实手机号
									storage.setPhone(res.data.data.phone);
									// #endif
									storage.setUserToken(res.data.data.token);
									// storage.setKey(res.data.data.key);
									console.log("静默登录成功，重新发起请求");
									doPost(options);
								} else {
									loginQuietlyFail();
								}
							},
							fail: (e) => {
								console.log("静默登录请求失败", e);
							},
							complete: () => {}
						})
					} else {
						loginQuietlyFail();
					}
				},
				fail: (res) => {
					uni.hideLoading()
					// this.$api.msg("登录失败");
				}
			})
		} else {
			options.success(res.data);
		}
	} else {
		console.error("访问返回结果异常", res);
	}
}

// accis码排序
function sort_ascii(obj) {
	let arr = new Array();
	let num = 0;
	for (let i in obj) {
		arr[num] = i;
		num++;
	}
	let sortArr = arr.sort();
	//let sortObj = {};    //完成排序值
	let str = ''; //自定义排序字符串
	for (let i in sortArr) {
		if (typeof obj[sortArr[i]] === 'object')
			str += sortArr[i] + '=' + JSON.stringify(obj[sortArr[i]]) + '&';
		else
			str += sortArr[i] + '=' + obj[sortArr[i]] + '&';
		//sortObj[sortArr[i]] = obj[sortArr[i]];
	}
	//去除两侧字符串
	let char = '&'
	str = str.replace(new RegExp('^\\' + char + '+|\\' + char + '+$', 'g'), '');
	return str;
	//return sortObj;
}
const loginQuietlyFail = () => {
	console.log('微信静默登录失败！');
	uni.hideLoading();
	uni.clearStorage();
	uni.showModal({
		title: "提示",
		content: "您的登录信息已过期，请重新登录",
		confirmText: "前往登录",
		showCancel: false,
		success(res) {
			let pagesAry = getCurrentPages();
			let length = pagesAry.length;
			let topPage = pagesAry[length - 1].route
			if ('pages/login/login' == topPage) {
				return
			}
			uni.navigateTo({
				url: '/pages/login/login'
			});
		}
	});
}


export http